#!/usr/bin/bash
#
# gen-backups.sh - A simple backup script.
#
# Description: This script isn't very "smart",
#              it'll backup the same old data
#              over and over. If you want "smart"
#              backups, run a CVS server (or write
#              your own script).
#
#              The point of this script is to offer
#              an alternative to backing up your whole
#              home directory, or doing everything
#              manually.
#
# Usage: Edit the below variables, then run it.
#        Each specified directory will have a
#        ".tar.bz2" archive in $BACDIR/$SUBDIR.
#
##

# Directory to store backups in.
BACDIR="/home/tom/backup"

# Name to use for the backup subdirectories.
SUBDIR=backup-$(date +%m%d%y)

# Directories to be backed up.
#
# You can add as many of these as you want,
# just make sure the index starts at zero
# and increments by one.
DIRS[0]="/home/tom/workspace"
DIRS[1]="/home/tom/school"
DIRS[2]="/home/tom/themes"
DIRS[3]="/home/tom/scripts"
DIRS[4]="/home/tom/Desktop"


# Don't edit anything below this line!

# Number of directories to backup.
NUMDIRS=${#DIRS[*]}

echo "Running backups script..."
cd "$BACDIR"
cd ..

# If the backup dir doesn't exist, create it.
if [ ! -d "$BACDIR" ]; 
then 
    mkdir "$BACDIR" 
fi

cd "$BACDIR"

# If the directory we want to make already
# exists, keep adding numbers into the name
# until we get a directory name that doesn't.
if [ -d "$SUBDIR" ];
then
    I=0

    while [ -d "$SUBDIR""_"$I ]
    do
	let I=$I+1
    done
    
    SUBDIR+="_"$I
fi

mkdir "$SUBDIR"

I=0

# Loop through and make backups.
while [ $I -lt $NUMDIRS ]
do
    # If the current directory we want to
    # backup exists, proceed.
    if [ -d "${DIRS[$I]}" ];
    then
	# Make a temporary file with a really
        # long name to avoid conflicts.
	MAGIC=".190427150621502"

        # Echo the name of the directory we're
        # backing up into the temp file
	echo "${DIRS[$I]}" > $MAGIC

        # Use sed to replace all '/' with '-',
        # and set NAME to "backup-<name-of-dir>".
	NAME="backup"$(sed -e 's/\//-/g' $MAGIC )

        # Remove the temporary file.
	rm $MAGIC

        # Make the backup.
	tar cjf "$BACDIR/$SUBDIR/$NAME".tar.bz2 "${DIRS[$I]}"
	echo "Backed up ($[$I+1]/$NUMDIRS) directories."

    # If the directory does not exist, or is a file
    # , throw an error.
    else
	echo "Error, directory \"${DIRS[$I]}\" does not exist or is not a directory."
    fi

    let I=$I+1
done

echo "Backups complete, have a nice day!"
